<template>
  <div>
    <el-drawer :title="knowledgeUnitName"
      size="50%"
      :modal="false"
      :visible.sync="drawerVisible"
      @close="contentEditFlag = false; drawerVisible = false">
      <el-button size="small" @click="editContent" v-html="contentEditFlag ? '保存' : '编辑'"></el-button>
      <div v-show="contentEditFlag" style="margin-top: 10px">
        <div style="width: 100px; display: inline-block; text-align: right; vertical-align: middle; ">知识单元名称: </div>
        <KindEditor style="width: 300px; display: inline-block; vertical-align: middle; " :content.sync="knowledgeUnitName" editor-type="Input"/>
      </div>
      <div :style="{backgroundColor : contentEditFlag ? 'aliceblue' : 'antiquewhite'}" ref="contentDiv" :contenteditable="contentEditFlag" v-html="knowledgeUnitContent"></div>
    </el-drawer>
    <el-row style="line-height: 40px; ">
      <el-col :span="8">
        <el-button icon="el-icon-back"
                   size="small"
                   type="text"
                   @click="$router.go(-1)">返回</el-button>
        <span> | 标注</span>
        <el-button size="small" type="danger" @click="deleteList">批量删除</el-button>
      </el-col>

      <el-col :span="8">
        <el-input size="small" v-model="keyWords" placeholder="请输入名称搜索">
          <i class="el-input__icon el-icon-search" slot="prefix"></i>
        </el-input>
      </el-col>

      <el-col :offset="2"
              :span="1">
        <span>类别</span>
      </el-col>
      <el-col :span="5">
        <el-select filterable
                   v-model="selectedCategory"
                   style="width: 99%; "
                   size="small">
          <el-option v-for="item in $store.state.knowledgeLibList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"></el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <el-table stripe
                 :height="tableHeight - 10"
                 show-checkbox
                 :data='filteredKnowledgeUnitPage'
                  @selection-change="handleSelectionChange">
          <el-table-column align="center"
            type="selection"
            width="50">
          </el-table-column>
          <el-table-column label="知识名称"
                           min-width="150"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-html="scope.row.name"/>
            </template>
          </el-table-column>
          <el-table-column label="所属目录"
                           prop="bookCatalogPath"
                           min-width="200"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="类别"
                           min-width="100"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-html="scope.row.categoryVo"/>
            </template>
          </el-table-column>
          <el-table-column label="分类标签"
                           min-width="200"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="white-space: pre-line;"
                    v-html="scope.row.tagVo" />
            </template>
          </el-table-column>
          <el-table-column label="自由标签"
                           min-width="150"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-html="scope.row.customTagVo"/>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           width="100">
            <template slot-scope="scope">
              <span>
                <el-link @click.prevent="detail(scope.row, 'knowledgeUnit')">详情</el-link>
              </span>
              <span>
                <el-link type="danger"
                         @click.prevent="deleteKnowledgeUnit(scope.row)">删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-pagination
            :page-size.sync="pageSize"
            :page-sizes="[5, 10, 15, 20, 50, 100]"
            @size-change="currentPage = 1"
            :current-page.sync="currentPage"
            :total="filteredKnowledgeUnitListLength"
            background
            layout="total, sizes, prev, pager, next, jumper"
            style="text-align: right;margin-top: 10px"></el-pagination>
        </el-row>
      </el-col>

      <el-col :span="8">
        <el-row :style="{height: tableHeight + 'px'}">
          <el-tabs active-name="tag"
                   style="margin-left: 5px; "
                   type="card"
                   :stretch="true">
            <el-tab-pane label="分类标签"
                         name="tag">
              <el-row style="line-height: 50px; margin: 0px 20px; "
                      v-for="(item,idx) in knowledgeLibFieldList"
                      :key="idx">
                <el-col :span="8">
                  <span class="tagLabel"
                        v-text="item.name"
                        :title="item.name"></span>
                </el-col>
                <el-col :span="16">
                  <el-cascader collapse-tags
                               :options="$store.state.tagTree.find(tag => tag.id === item.kindValue).children"
                               v-model="item.property"
                               :props="{value: 'id', label: 'name', multiple: true, checkStrictly: true}"
                               filterable
                               style="width: 100%; "></el-cascader>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="自由标签"
                         name="customTag"
                         style="text-align: center">
              <MultiValueBox :fieldValue.sync="customTag"/>
            </el-tab-pane>
          </el-tabs>
        </el-row>
        <div style="float: right">
          <el-button size="small"
                     @click='saveMark'
                     type="primary">确定</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import MultiValueBox from "../knowledge/knowledgeEdit/MultiValueBox"
  import {mapState} from 'vuex'
  export default {
    name: "MarkKnowledgeUnit",
    components: {
      MultiValueBox,
    },
    data() {
      return {
        tableHeight: CONST.WORKSPACE_HEIGHT - 85,
        selectedCategory: '',
        customTag: [],
        keyWords: '',
        drawerVisible: false,
        knowledgeUnitName: '',
        knowledgeUnitContent: '',
        knowledgeLibFieldList: [],
        crtRow: {},
        contentEditFlag: false,
        currentPage: 1,
        pageSize: 10,
        knowledgeUnitSelection: [],
      }
    },
    computed: {
      ...mapState(['knowledgeUnitList']),
      filteredKnowledgeUnitListLength() {
        return this.knowledgeUnitList.filter(item => item.name.search(this.keyWords) !== -1).length
      },
      filteredKnowledgeUnitPage() {
        return this.knowledgeUnitList.filter(item => item.name.search(this.keyWords) !== -1)
          .slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
      },
    },
    methods: {
      deleteList() {
        if (this.knowledgeUnitSelection.length === 0) {
          this.$message.warning("请选中待删除知识单元")
          return
        }
        this.$confirm('确认删除选中知识单元?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.post('/pmph/action/knowledgeUnit/deleteList', this.knowledgeUnitSelection.map(item => item.id))
            .then(() => {
              for (let knowledgeUnit of this.knowledgeUnitSelection) {
                this.knowledgeUnitList.remove(knowledgeUnit)
              }
            })
        })
      },
      editContent() {
        if (this.contentEditFlag) {
          this.crtRow.content = this.$refs.contentDiv.innerHTML
          this.crtRow.name = this.knowledgeUnitName
          this.drawerVisible = false
          this.axios.post('/pmph/action/knowledgeUnit/updateById', this.crtRow)
            .then(() => {
            })
        }
        this.contentEditFlag = !this.contentEditFlag
      },
      handleSelectionChange(selection) {
        this.knowledgeUnitSelection = selection
        if (this.knowledgeUnitSelection.length === 1) {
          let knowledgeUnit = this.knowledgeUnitSelection[0]
          this.selectedCategory = knowledgeUnit.category
          this.customTag = knowledgeUnit.customTag
          for (let field of this.knowledgeLibFieldList) {
            field.property = knowledgeUnit.tag[field.kindValue]
          }
        }
      },
      saveMark() {
        if (this.knowledgeUnitSelection.length === 0) {
          this.$message.warning("请选中知识单元")
          return
        }
        let selectedKnowledgeUnitList = JSON.parse(JSON.stringify(this.knowledgeUnitSelection))
        this.$confirm("确认覆盖选中知识单元的标注?", '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 组装数据;
          // 组装分类标签字段;
          let tag = {}
          for (let tagField of this.knowledgeLibFieldList) {
            tag[tagField.kindValue] = tagField.property
          }
          for (let knowledgeUnit of selectedKnowledgeUnitList) {
            knowledgeUnit.category = this.selectedCategory
            knowledgeUnit.tag = tag
            knowledgeUnit.customTag = this.customTag
          }
          this.axios.post('/pmph/action/knowledgeUnit/saveMark', selectedKnowledgeUnitList)
            .then((response) => {
              // 根据返回值更新knowledgeUnit;
              for (let i = 0; i < selectedKnowledgeUnitList.length; i++) {
                let selectedKnowledgeUnit = selectedKnowledgeUnitList[i]
                let selectedIndex = this.knowledgeUnitList.findIndex(item => item.id === selectedKnowledgeUnit.id)
                let responseKnowledgeUnit = response.data.find(item => item.id === selectedKnowledgeUnit.id);
                this.$set(this.knowledgeUnitList, selectedIndex, responseKnowledgeUnit)
              }
            })
        })
      },
      detail(tableRow) {
        this.crtRow = tableRow
        this.knowledgeUnitContent = tableRow.content
        this.knowledgeUnitName = tableRow.name
        this.drawerVisible = true
      },
      deleteKnowledgeUnit(tableRow){
        this.$confirm('确认删除知识单元?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.post('/pmph/action/knowledgeUnit/deleteById', {
            id: tableRow.id
          }).then(() => {
            let findIndex = this.knowledgeUnitList.findIndex(item => item.id === tableRow.id);
            this.knowledgeUnitList.splice(findIndex, 1)
          })
        })
      },
    },
    watch: {
      selectedCategory(){
        this.axios.get('/pmph/action/knowledgeLib/selectTagFieldList', {
          params: {
            knowledgeLibId: this.selectedCategory,
          }
        }).then(response => {
          this.knowledgeLibFieldList = response.data
          if (this.knowledgeUnitSelection.length === 1) {
            let knowledgeUnit = this.knowledgeUnitSelection[0]
            for (let field of this.knowledgeLibFieldList) {
              field.property = knowledgeUnit.tag[field.kindValue]
            }
          }
        })
      }
    },
  }
</script>

<style scoped>
  /deep/ .el-drawer__body {
    overflow: auto;
    margin: 0px 20px;
  }
  .tagLabel{
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space:nowrap;
    width:100%;
    display:block;
  }
</style>
